<template>
  <div class="container-header-margin content">
    <div>
      <a-row>
        <a-col :span="4"></a-col>
        <a-col :span="16">
          <div class="title">团队信息</div>

          <!-- 教师团队信息表格 -->
          <div class="table-section">
            <div class="section-title">教师信息</div>
            <a-table :dataSource="teacherTeam" :columns="teacherColumns" :pagination="{ pageSize: 5 }" bordered>
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'sex'">
                  {{ record.sex === 1 ? '男' : '女' }}
                </template>
                <template v-if="column.key === 'isTeacher'">
                  {{ record.isTeacher === 1 ? '教师' : '学生' }}
                </template>
              </template>
            </a-table>
          </div>

          <!-- 学生团队信息表格 -->
          <div class="table-section">
            <div class="section-title">学生信息</div>
            <a-table :dataSource="studentTeam" :columns="studentColumns" :pagination="{ pageSize: 5 }" bordered>
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'sex'">
                  {{ record.sex === 1 ? '男' : '女' }}
                </template>
                <template v-if="column.key === 'isTeacher'">
                  {{ record.isTeacher === 1 ? '教师' : '学生' }}
                </template>
              </template>
            </a-table>
          </div>

          <div style="text-align: center">
            <a-space>
              <a-button size="large" @click="addMember" type="primary">邀请成员</a-button>
              <a-button size="large">修改报名材料</a-button>
              <a-button size="large" @click="jump('/ss')">返回上一页</a-button>
            </a-space>
          </div>

          <!-- 添加成员模态框 -->
          <a-modal v-model:open="memberModalVisible" title="批量添加团队成员" @ok="submitAddMembers"
            :confirm-loading="memberLoading" width="700px">
            <div class="batch-add-container">
              <!-- 左侧：团队选择和成员查询 -->
              <div class="search-section">
                <a-form layout="vertical" :model="memberForm">
                  <a-form-item label="选择团队" name="teamId" :rules="[{ required: true, message: '请选择要添加成员的团队' }]">
                    <a-select v-model:value="memberForm.teamId" style="width: 100%" placeholder="请选择要添加成员的团队"
                      :loading="teamsLoading">
                      <a-select-option v-for="team in userTeams" :key="team.id" :value="team.id">
                        {{ team.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="学号" name="studentNumber" :rules="[{ required: true, message: '请输入学号' }]">
                    <a-input-search v-model:value="memberForm.studentNumber" placeholder="请输入学号"
                      @search="searchStudentInfo" :loading="searchLoading" enter-button="查询" allow-clear />
                  </a-form-item>

                  <!-- 查询结果展示 -->
                  <div class="student-info-card" v-if="memberForm.studentName">
                    <div class="student-info">
                      <div class="info-row">
                        <span class="label">姓名:</span>
                        <span class="value">{{ memberForm.studentName }}</span>
                      </div>
                      <div class="info-row">
                        <span class="label">学院:</span>
                        <span class="value">{{ memberForm.collegeName }}</span>
                      </div>
                      <div class="info-row">
                        <span class="label">专业:</span>
                        <span class="value">{{ memberForm.majorName }}</span>
                      </div>
                    </div>
                    <a-button type="primary" size="small" @click="addToList" :disabled="isStudentAdded">
                      {{ isStudentAdded ? '已添加' : '添加到列表' }}
                    </a-button>
                  </div>

                  <div v-if="userNotFound" class="error-message">
                    未找到该学号对应的学生信息，请检查学号是否正确
                  </div>
                </a-form>
              </div>

              <!-- 右侧：已添加成员列表 -->
              <div class="members-list-section">
                <div class="section-header">
                  <h3>已添加成员 ({{ selectedMembers.length }})</h3>
                  <a-button type="link" @click="clearSelectedMembers" :disabled="selectedMembers.length === 0">
                    清空列表
                  </a-button>
                </div>

                <div class="empty-list" v-if="selectedMembers.length === 0">
                  <a-empty description="暂无添加成员" />
                </div>

                <div class="members-list" v-else>
                  <div v-for="(member, index) in selectedMembers" :key="index" class="member-item">
                    <div class="member-info">
                      <div class="member-name">{{ member.name }}</div>
                      <div class="member-details">{{ member.collegeName }} · {{ member.majorName }}</div>
                    </div>
                    <a-button type="text" danger @click="removeFromList(index)">
                      <template #icon><delete-outlined /></template>
                    </a-button>
                  </div>
                </div>
              </div>
            </div>

            <div class="batch-info">
              <info-circle-outlined />
              <span>批量添加说明: 查询学生后点击"添加到列表"，可添加多名成员，完成后点击"确定"提交</span>
            </div>
          </a-modal>
        </a-col>
        <a-col :span="4"></a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from "@/store/user";
import { SYSYTM_TITLE } from "@/config";
import { reactive, ref, toRaw } from "vue";
import { message, Modal } from "ant-design-vue";
import { DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';
import {
  getTeamMember,
  addTeamMember,
  getUserInfoByNumber,
  getUserTeams,
  get_title
} from "@/apis";
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 团队成员添加相关变量
const memberModalVisible = ref(false);
const memberLoading = ref(false);
const searchLoading = ref(false);
const userNotFound = ref(false);
const teamsLoading = ref(false); // 添加团队加载状态
const userTeams = ref([]);
const selectedMembers = ref([]);

const memberForm = reactive({
  teamId: null,       // 添加团队ID字段
  studentNumber: '',
  studentName: '',
  collegeName: '',
  majorName: '',
  reason: '',
  userId: '',        // 保留原有选择原因字段
  fullData: null    // 新增完整学生数据字段
});

// 计算当前查询的学生是否已添加到列表
const isStudentAdded = computed(() => {
  if (!memberForm.userId) return false;
  return selectedMembers.value.some(member => member.id === memberForm.userId);
});
useSeoMeta({
  title: "教师报名-" + SYSYTM_TITLE,
  description: SYSYTM_TITLE,
  keywords: "白云学院,创新创业网",
  robots: "index, follow",
  canonical: "https://example.com",
});

const studentTeam = ref([]);
const teacherTeam = ref([]);
//获取职称字典
async function getTitle() {
  const res = await get_title();
  teacherTeam.value.map(item => {
    item.title = res.rows.find(x => Number(x.dictValue) === item.title)?.dictLabel || '无';
  })
}
// 获取团队成员信息
async function getTeam(teamId) {
  if (!teamId) {
    console.warn('未提供团队ID，无法获取团队成员');
    return;
  }
  let pageNum = 1;
  let pageSize = 10;
  try {
    const res = await getTeamMember(teamId, { pageNum, pageSize });
    if (res.code === 200 && res.data) {
      studentTeam.value = res.data.student;
      teacherTeam.value = res.data.teacher;
      // console.log('teacherTeam.value', teacherTeam.value);
      // console.log('studentTeam.value', studentTeam.value);
    } else {
      message.error(res.msg || '获取团队成员失败');
    }
  } catch (error) {
    console.error('获取团队成员失败', error);
    message.error('获取团队成员失败，请稍后重试');
  }
}

// 获取用户已创建的团队
const fetchUserTeams = async () => {
  try {
    if (!userStore.userInfo) {
      console.warn('用户未登录或用户信息未加载');
      message.warning('请先登录后再操作');
      return;
    }

    teamsLoading.value = true;
    const params = {
      userId: userStore.userInfo?.id,
    }
    const res = await getUserTeams(params);
    // console.log('res', res);

    if (res.code === 200 && res.rows && res.rows.length > 0) {
      userTeams.value = res.rows;
      // 如果有团队，设置第一个为当前团队
      if (memberForm.teamId === null) {
        memberForm.teamId = res.rows[0].id;
      }
    } else {
      userTeams.value = [];
    }
  } catch (error) {
    console.error('获取用户团队失败', error);
  } finally {
    teamsLoading.value = false;
  }
};

// 搜索学生信息函数
const searchStudentInfo = async () => {
  if (!memberForm.studentNumber) {
    message.warning('请输入学号');
    return;
  }

  searchLoading.value = true;
  userNotFound.value = false;

  try {
    //根据学号查询学生信息
    const res = await getUserInfoByNumber(memberForm.studentNumber);
    if (res.code === 200 && res.data) {
      memberForm.studentName = res.data.name;
      memberForm.userId = res.data.id;
      memberForm.collegeName = res.data.collegeName;
      memberForm.majorName = res.data.majorName;
      memberForm.fullData = res.data;
    } else {
      userNotFound.value = true;
      memberForm.studentName = '';
      memberForm.userId = '';
      memberForm.collegeName = '';
      memberForm.majorName = '';
      memberForm.fullData = null;
    }
  } catch (error) {
    console.error('查询学生信息失败', error);
    userNotFound.value = true;
  } finally {
    searchLoading.value = false;
  }
};

// 添加学生到列表
const addToList = () => {
  if (!memberForm.userId || !memberForm.studentName) {
    message.warning('请先查询有效的学生信息');
    return;
  }

  if (isStudentAdded.value) {
    message.info('该学生已在添加列表中');
    return;
  }

  // 直接添加完整的学生数据对象到选择列表
  const studentData = {
    ...memberForm.fullData,
    // 确保展示所需的关键字段存在
    name: memberForm.studentName,
    number: memberForm.studentNumber,
    reason: memberForm.reason || '团队邀请'
  };

  selectedMembers.value.push(studentData);

  message.success(`已添加 ${memberForm.studentName} 到列表`);

  // 清空当前查询，准备下一个
  memberForm.studentNumber = '';
  memberForm.studentName = '';
  memberForm.userId = null;
  memberForm.collegeName = '';
  memberForm.majorName = '';
  memberForm.reason = '';
  memberForm.fullData = null;
  userNotFound.value = false;
};

// 从列表中移除学生
const removeFromList = (index) => {
  const removedMember = selectedMembers.value[index];
  selectedMembers.value.splice(index, 1);
  message.success(`已从列表中移除 ${removedMember.name}`);
};

// 清空已选列表
const clearSelectedMembers = () => {
  if (selectedMembers.value.length === 0) return;

  Modal.confirm({
    title: '确认清空',
    content: '确定要清空所有已添加的成员吗？',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      selectedMembers.value = [];
      message.success('已清空添加列表');
    }
  });
};

// 提交添加成员
const submitAddMembers = async () => {
  // 检查团队选择
  if (!memberForm.teamId) {
    message.warning('请选择要添加成员的团队');
    return;
  }

  // 检查是否有成员要添加
  if (selectedMembers.value.length === 0) {
    message.warning('请至少添加一名成员');
    return;
  }

  memberLoading.value = true;

  try {
    // 准备请求参数，包含所有已选成员
    const params = {
      teamId: memberForm.teamId,
      userInfoVoList: selectedMembers.value
    };

    const res = await addTeamMember(params);

    if (res.code === 200) {
      const teamName = userTeams.value.find(t => t.id === memberForm.teamId)?.name || '当前团队';
      message.success(`已成功邀请 ${selectedMembers.value.length} 名成员加入 ${teamName}`);
      memberModalVisible.value = false;

      // 重置表单和已选列表
      resetMemberForm();
      selectedMembers.value = [];

      // 刷新团队成员列表
      getTeam(memberForm.teamId);
    } else {
      message.error(res.msg || '添加成员失败，请检查是否有成员已在团队中');
    }
  } catch (error) {
    console.error('添加成员失败', error);
    message.error('添加成员失败，请稍后重试');
  } finally {
    memberLoading.value = false;
  }
};

// 重置成员表单
const resetMemberForm = () => {
  // 保留团队ID，方便连续添加成员
  const teamId = memberForm.teamId;

  memberForm.studentNumber = '';
  memberForm.studentName = '';
  memberForm.userId = null;
  memberForm.collegeName = '';
  memberForm.majorName = '';
  memberForm.reason = '';
  memberForm.fullData = null;

  // 恢复之前选择的团队ID
  memberForm.teamId = teamId;

  userNotFound.value = false;
};

// 添加成员函数
function addMember() {

  if (userTeams.value.length === 0) {
    Modal.confirm({
      title: '您尚未创建团队',
      content: '添加成员前需要先创建一个团队，是否现在创建团队？',
      okText: '创建团队',
      cancelText: '取消',
      onOk: () => {
        // 跳转到创建团队页面
        router.push('/ss/dc/student');
      }
    });
    return;
  }

  // 打开模态框
  memberModalVisible.value = true;
};

onMounted(async () => {
  try {

    await fetchUserTeams();
    // 确保已获取到团队ID后再获取团队成员
    if (memberForm.teamId) {
      await getTeam(memberForm.teamId);
      getTitle();
    } else {
      message.warning('未找到可用的团队，请先创建团队');
    }
  } catch (error) {
    console.error('初始化页面失败', error);
  }
})

// 教师表格列定义
const teacherColumns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '工号',
    dataIndex: 'number',
    key: 'number',
    width: 120,
  },
  {
    title: '所在学院',
    dataIndex: 'collegeName',
    key: 'collegeName',
    width: 150,
  },
  {
    title: '专业',
    dataIndex: 'majorName',
    key: 'majorName',
    width: 150,
  },
  {
    title: '职称',
    dataIndex: 'title',
    key: 'title',
    width: 100,
  },
  {
    title: '指导队伍数',
    dataIndex: 'teamNum',
    key: 'teamNum',
    width: 100,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 180,
  }
];

// 学生表格列定义
const studentColumns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '学号',
    dataIndex: 'number',
    key: 'number',
    width: 120,
  },
  {
    title: '所在学院',
    dataIndex: 'collegeName',
    key: 'collegeName',
    width: 150,
  },
  {
    title: '专业',
    dataIndex: 'majorName',
    key: 'majorName',
    width: 150,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 180,
  }
];
</script>

<style lang="less" scoped>
.content {
  min-height: 90vh;
  padding: 20px;
}

.title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.table-section {
  margin-bottom: 30px;

  .section-title {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-left: 10px;

  }
}

:deep(.ant-table) {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f5f7fa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr > td) {
  word-break: break-all;
}

@media (max-width: 768px) {
  .content {
    padding: 10px;
  }

  :deep(.ant-table) {
    width: 100%;
    overflow-x: auto;
  }
}

/* 批量添加模态框样式 */
.batch-add-container {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;

  .search-section {
    flex: 1;
    border-right: 1px solid #f0f0f0;
    padding-right: 20px;
  }

  .members-list-section {
    flex: 1;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
      }
    }

    .members-list {
      max-height: 300px;
      overflow-y: auto;

      .member-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .member-info {
          .member-name {
            font-weight: 500;
          }

          .member-details {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }

  .student-info-card {
    background-color: #f5f5f5;
    border-radius: 4px;
    padding: 12px;
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .student-info {
      .info-row {
        margin-bottom: 4px;

        .label {
          font-weight: 500;
          margin-right: 8px;
        }
      }
    }
  }
}

.batch-info {
  background-color: #f9f9f9;
  padding: 8px 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;

  .anticon {
    color: #1890ff;
  }
}

.empty-list {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-message {
  color: #ff4d4f;
  margin-top: 8px;
}
</style>